#!/usr/bin/env python

import asyncio
import datetime
import random
import websockets

CONNECTIONS = set()

async def register(websocket):
    CONNECTIONS.add(websocket)

    async for message in websocket:
        print(message)
        websockets.broadcast(CONNECTIONS, message)


    try:
        await websocket.wait_closed()
    finally:
        CONNECTIONS.remove(websocket)


async def show_time():
    while True:
        message = datetime.datetime.utcnow().isoformat() + "Z"
        # websockets.broadcast(CONNECTIONS, message)
        await asyncio.sleep(random.random() * 2 + 1)

# async def echo(websocket):
#     async for message in websocket:
        # print(message)
        # await websocket.send(message)


async def main():
    async with websockets.serve(register, "127.0.0.1", 5678):
        await show_time()
         # await echo(CONNECTIONS)


if __name__ == "__main__":
    asyncio.run(main())


'''
#客户端

async def hello(msg):
    async with websockets.connect('ws://192.168.1.57:5678') as websocket:
        await websocket.send(msg)


asyncio.run(hello(f"{msg}"))
'''